package com.jjyd.crlp.services.impl;

import com.jjyd.crlp.domain.repository.DictionaryRepo;
import com.jjyd.crlp.domain.repository.NewsRepo;
import com.jjyd.crlp.model.dto.tech.WordDto;
import com.jjyd.crlp.services.TechService;
import com.jjyd.crlp.util.check.CheckUtil;
import com.jjyd.crlp.util.news.GetNewsUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class TechServiceImpl implements TechService {

    @Autowired
    private DictionaryRepo dictionaryRepo;
    @Autowired
    private NewsRepo newsRepo;

    private static final String GET_NEWS_THREAD = "getNewsThread";

    /**
     * 添加单词
     *
     * @param wordDto 单词内容
     * @return 返回添加单词的id
     */
    @Override
    public Integer addWord(WordDto wordDto) {
        Integer id = dictionaryRepo.save(wordDto.toDictionary()).getId();
        return id;
    }

    /**
     * 获取新闻
     *
     * @return
     */
    @Override
    public Boolean getNews() {


        ThreadGroup currentGroup = Thread.currentThread().getThreadGroup();
        int noThreads = currentGroup.activeCount();
        Thread[] lstThreads = new Thread[noThreads];
        currentGroup.enumerate(lstThreads);
        for (int i = 0; i < noThreads; i++) {
            System.out.println("线程号：" + i + " = " + lstThreads[i].getName());
            if (GET_NEWS_THREAD.equals(lstThreads[i].getName())) {
                CheckUtil.check("已经启动线程，不可以再次启动", false);
            }
        }


        //创建线程要执行爬取网站的任务
		Runnable r1 = new GetNewsUtil(newsRepo);
		//创建线程
		Thread t1 = new Thread(r1);
		t1.setName(GET_NEWS_THREAD);
		t1.start();
        return true;
    }
}
